package game.leon.engine.data;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 代码生成工具
 * User: bianpeng
 * Date: 12-2-2
 */
public class CodeGen {
    private Logger logger = Logger.getLogger(getClass());
    private VelocityEngine engine;
    private CodeGen() {
        engine = new VelocityEngine();
        engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        engine.setProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
        engine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
        engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        engine.setProperty("runtime.log.logsystem.log4j.logger", "root");
        engine.init();
    }
    private static CodeGen instance;
    public static CodeGen getInstance() {
        if (instance == null) {
            instance = new CodeGen();
        }
        return instance;
    }
    public <T> void make(String templatePath, String outputPath, VelocityContext context) {
        Template template = engine.getTemplate(templatePath, "utf-8");
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outputPath), "utf-8"));
            make(template, writer, context);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        } catch (FileNotFoundException e) {
            logger.error("", e);
        } catch (IOException e) {
            logger.error("", e);
        }
    }
    public <T> void make(String templatePath, String outputPath, Map<String, ?> model) {
        VelocityContext context = new VelocityContext();
        for(Map.Entry<String, ?> entry : model.entrySet()) {
            context.put(entry.getKey(), entry.getValue());
        }
        make(templatePath, outputPath, context);
    }
    public <T> void make(String templatePath, String outputPath, List<T> items) {
        VelocityContext context = new VelocityContext();
        context.put("items", items);
        make(templatePath, outputPath, context);
    }
    private void make(Template template, Writer writer, VelocityContext context) {
        template.merge(context, writer);
    }
}
